package com.wawayaya.parentteacher.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.creative.accountsdk.widget.AvatarView;
import com.wawayaya.api.ApiResponseData;
import com.wawayaya.api.interf.ApiResponseJsonListener;
import com.wawayaya.api.remote.ApiParentTeacher;
import com.wawayaya.base.BaseActivity;
import com.wawayaya.util.ImageUtils;
import com.wawayaya.util.TLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wawayaya.kids_iread.R;

/**
 *
 * 家长中心 /教师中心 MainActivity
 *
 * Created by chang_sheng on 2015/12/7.
 */
public class TeacherParentMainActivity  extends BaseActivity  implements ApiResponseJsonListener {

    private LinearLayout ad_layout;
    private ViewPager viewPager;
    private List<ImageView> bannerImglist;
    private ImageView[] icons;
    private boolean loopPlayState=false;
    private LinearLayout hor_layout;
    private LayoutInflater mInflater;
    private LinearLayout.LayoutParams imgvwDimens;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what=msg.what;
            switch (what){

            }
        }
    };
    @Override
    protected void init(Bundle savedInstanceState) {
        setContentView(R.layout.teacher_parent_main_layout);

    }

    @Override
    public void initView() {
        ad_layout=(LinearLayout)findViewById(R.id.pt_banner_layout_dot);
        viewPager=(ViewPager)findViewById(R.id.pt_banner_viewpager);
        bannerImglist=new ArrayList<>();
        hor_layout=(LinearLayout)findViewById(R.id.tp_hori_layout);
        mInflater=LayoutInflater.from(context);
    }

    @Override
    public void initData() {
         //下载数据
         loadData();

    }

    @Override
    public void setListener() {

    }

    @Override
    public void onClick(View v) {

    }
    // 初始化指示性图标
    private void initDot() {
        // 创建存储小圆点的数组对象
        icons = new ImageView[bannerImglist.size()];
        // 循环获得小圆点，并初始化图片
        int dimens = 10;
        float density = getResources().getDisplayMetrics().density;
        int finalDimens = (int) (dimens * density);
        imgvwDimens = new LinearLayout.LayoutParams(finalDimens, finalDimens);
        //设置圆点间距
        imgvwDimens.setMargins(5,0,5,0);
        for (int i = 0; i < icons.length; i++) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageResource(R.drawable.home_icon_bannergraypoint);
            imageView.setLayoutParams(imgvwDimens);
            //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ad_layout.addView(imageView);
            icons[i] = (ImageView) ad_layout.getChildAt(i);
            icons[i].setTag(i);
            icons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewPager.setCurrentItem((Integer) v.getTag());
                }
            });
        }
    }
    private void  loadData(){
        ApiParentTeacher.indexChome(context, this);
    }

    @Override
    public void success1(ApiResponseData result) {
        Log.i("tpData", result.getRetinfo().toString());
        String jsonString=result.getRetinfo().toString();
        //广告部分
        bannerPart(jsonString);
        //添加孩子部分
        addChildPart(jsonString);


    }
     //添加孩子部分
    private void addChildPart(String jsonString) {
        try {
            JSONObject obj=new JSONObject(jsonString);
            JSONObject obj2=obj.getJSONObject("uinfo");
            JSONObject obj3=new JSONObject(obj2.getString("user"));
            View view=mInflater.inflate(R.layout.pt_uinfo_item, null);
            AvatarView img=(AvatarView)findViewById(R.id.tp_info_item_img);
            TextView tv=(TextView)findViewById(R.id.tp_info_item_tv);
            String imgUrl=obj3.getString("avatar");
            Log.i("imgUrl", imgUrl);
            /*String sub="null";
            int a=imgUrl.indexOf(sub);
            if(a>=0){
                img.setImageResource(com.creative.accountsdk.R.drawable.regsetting_img_girl);
            }else{
                //不存在
                img.setUinfoUrl(imgUrl);
            }
            Log.i("nicknameString", obj3.getString("nickname"));
            tv.setText(obj3.getString("nickname"));*/
            hor_layout.addView(view);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //广告部分
    private void bannerPart(String jsonString) {
        try {
            JSONObject obj=new JSONObject(jsonString);
            JSONArray arr=obj.getJSONArray("banner");
            for (int i=0;i<arr.length();i++){
                JSONObject obj2=arr.getJSONObject(i);
                ImageView imageView=new ImageView(getApplicationContext());
                ImageUtils.getImageLoader().displayImage(obj2.getString("img_uri"),imageView);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                bannerImglist.add(imageView);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyPagerAdapter adapter = new MyPagerAdapter();
        if (!loopPlayState){
            viewPager.setCurrentItem(0);
            handler.postDelayed(loopPlay, 3000);
            loopPlayState = true;
        }
        viewPager.setAdapter(adapter);
        // 初始化小圆点
        initDot();
        //给ViewPage添加页面切换（滚动）的事件 监听
        viewPagerListenter();
    }

    @Override
    public void success0(ApiResponseData result) {

    }

    @Override
    public void error(ApiResponseData result) {

    }

    class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return bannerImglist.size();
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            container.addView(bannerImglist.get(position));
            return bannerImglist.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(bannerImglist.get(position));
        }
    }
    //广告页轮播子线程
    Runnable loopPlay = new Runnable() {
        @Override
        public void run() {
            int position = viewPager.getCurrentItem();
            if (position == (bannerImglist.size() - 1)) {
                position = 0;
                viewPager.setCurrentItem(position);
            } else {
                viewPager.setCurrentItem(++position);
            }
            handler.postDelayed(loopPlay, 3000);
        }
    };
    private void viewPagerListenter() {
        // 给ViewPage添加页面切换（滚动）的事件
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            // 页面选中调用该方法
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < icons.length; i++) {
                    icons[i].setImageResource(R.drawable.home_icon_bannergraypoint);
                    icons[i].setLayoutParams(imgvwDimens);
                    icons[i].setScaleType(ImageView.ScaleType.CENTER_CROP);
                }
                icons[position].setImageResource(R.drawable.home_icon_bannerwhitepoint);
                icons[position].setLayoutParams(imgvwDimens);
                icons[position].setScaleType(ImageView.ScaleType.CENTER_CROP);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }
}
